package cn.wsalix.weixin.util;

import java.io.IOException;
import java.security.KeyManagementException;
import java.security.NoSuchAlgorithmException;
import java.security.cert.X509Certificate;

import javax.net.ssl.SSLContext;
import javax.net.ssl.TrustManager;
import javax.net.ssl.X509TrustManager;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.ResponseHandler;
import org.apache.http.client.config.RequestConfig;
import org.apache.http.client.methods.CloseableHttpResponse;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.conn.ssl.SSLConnectionSocketFactory;
import org.apache.http.impl.client.CloseableHttpClient;
import org.apache.http.impl.client.HttpClientBuilder;
import org.apache.http.impl.client.HttpClients;
import org.apache.http.util.EntityUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import cn.wsalix.weixin.servlet.WeixinSupport;

public class HttpUtil {
	private static HttpComponent htc = new HttpComponent();
	private static final Logger logger = LoggerFactory
			.getLogger(HttpUtil.class);
	private CloseableHttpClient createHttpsClient() {
		X509TrustManager x509mgr = new X509TrustManager() {
			@Override
			public void checkClientTrusted(X509Certificate[] xcs, String string) {
			}

			@Override
			public void checkServerTrusted(X509Certificate[] xcs, String string) {
			}

			@Override
			public X509Certificate[] getAcceptedIssuers() {
				return null;
			}
		};
		SSLContext sslContext = null;
		try {
			sslContext = SSLContext.getInstance("TLS");
		} catch (NoSuchAlgorithmException e1) {
			e1.printStackTrace();
		}
		try {
			sslContext.init(null, new TrustManager[] { x509mgr }, null);
		} catch (KeyManagementException e) {
			e.printStackTrace();
		}
		SSLConnectionSocketFactory sslsf = new SSLConnectionSocketFactory(
				sslContext, new String[] { "TLSv1" }, null,
				SSLConnectionSocketFactory.getDefaultHostnameVerifier());
		return HttpClients.custom().setSSLSocketFactory(sslsf).build();

	}

	public static String httpsGet(String httpsUrl) {
		CloseableHttpClient httpclient = htc.createHttpsClient();
		HttpGet httpGet = new HttpGet(httpsUrl);
		try {
			HttpResponse httpResp = httpclient.execute(httpGet);
			int statusCode = httpResp.getStatusLine().getStatusCode();
			if (statusCode == 200) {
				return EntityUtils.toString(httpResp.getEntity());
			}
		} catch (Exception e) {
			e.printStackTrace();
		} finally {
			httpGet.releaseConnection();
		}
		return null;

	}

	public String get(String url) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpGet httpget = new HttpGet(url);
		try {
			ResponseHandler<String> responseHandler = new ResponseHandler<String>() {
				@Override
				public String handleResponse(final HttpResponse response)
						throws ClientProtocolException, IOException {
					int status = response.getStatusLine().getStatusCode();
					if (status >= 200 && status < 300) {
						HttpEntity entity = response.getEntity();
						return entity != null ? EntityUtils.toString(entity)
								: null;
					} else {
						throw new ClientProtocolException(
								"Unexpected response status: " + status);
					}
				}

			};
			String responseBody = httpclient.execute(httpget, responseHandler);
			System.out.println(responseBody);
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			httpget.releaseConnection();
		}
		return url;
	}

	public String post(String url) {
		CloseableHttpClient httpclient = HttpClients.createDefault();
		HttpPost httppost = new HttpPost(url);
		try {
			// httppost.setEntity(reqEntity);

			CloseableHttpResponse response = httpclient.execute(httppost);
			logger.info("----------------------------------------");
			System.out.println(response.getStatusLine());
			EntityUtils.consume(response.getEntity());
		} catch (ClientProtocolException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} finally {
			httppost.releaseConnection();
		}
		return "";
	}

	public HttpPost createHttpPost(String url) {
		HttpPost httpPost = new HttpPost(url);
		httpPost.setHeader("Accept",
				"text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8");
		httpPost.setHeader("Accept-Encoding", "gzip, deflate");
		httpPost.setHeader("Accept-Language", "zh-CN,zh;q=0.8");
		httpPost.setHeader("Cache-Control", "max-age=0");
		httpPost.setHeader("Connection", "keep-alive");
		httpPost.setHeader("Content-Type", "application/x-www-form-urlencoded");
		httpPost.setHeader(
				"User-Agent",
				"Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/41.0.2272.101 Safari/537.36");

		return httpPost;
	}

	public static HttpResponse post(String url, HttpEntity entity,
			String sessionId) {
		// 创建HttpClientBuilder
		HttpClientBuilder httpClientBuilder = HttpClientBuilder.create();
		// HttpClient
		CloseableHttpClient closeableHttpClient = httpClientBuilder.build();
		// 依次是目标请求地址，端口号,协议类型
		RequestConfig reqConfig = RequestConfig.custom().build();
		// 请求地址
		HttpPost httpPost = new HttpPost(url);
		httpPost.setConfig(reqConfig);
		if (sessionId != null && !sessionId.equals("")) {
			httpPost.setHeader("Cookie", "JSESSIONID=" + sessionId);
		}
		try {
			httpPost.setEntity(entity);
			CloseableHttpResponse response = closeableHttpClient
					.execute(httpPost);
			// closeableHttpClient.close();
			return response;

		} catch (Exception e) {
			e.printStackTrace();
		}
		return null;
	}

	public static HttpResponse post(String url, HttpEntity entity) {
		/*
		 * UrlEncodedFormEntity entity; entity = new
		 * UrlEncodedFormEntity(params, "UTF-8");
		 */
		return post(url, entity, "");
	}

	public static HttpResponse get(String url, String sessionId) {
		CloseableHttpClient client = HttpClients.custom().build();
		// 请求地址
		HttpGet httpGet = new HttpGet(url);
		if (sessionId != null && !sessionId.equals("")) {
			httpGet.setHeader("Cookie", "JSESSIONID=" + sessionId);
		}
		try {
			return client.execute(httpGet);
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}
		return null;
	}
}
